<?php

/* Portal Pracy - praca magisterska
 * autor: Tomek Ceszke
 * email: tomek.ceszke@gmail.com
 * Politechnika Koszalińska 2007
 */

class CompaniesController extends AppController
{
	var $name 					= 'Companies';
	var $components 			= array('Image');
	var $othAuthRestrictions 	= array('add','edit','uhide','employer','view_emp');


	function index()
	{
		$defCriteria = aa(
				"Company.status",'1'
				);

		$criteria = aa(
				"Company.status",'1'
				);						
														
			//kategoria
		if(isset($this->params['url']['data']['Company']['name'])  AND !empty($this->params['url']['data']['Company']['name'])) 
		{
			$criteria['Company.name'] = "LIKE ".$this->params['url']['data']['Company']['name']."%";									  
		}
		
		if(isset($this->params['form']['data']['Company']['name'])  AND !empty($this->params['form']['data']['Company']['name'])) 
		{
			$criteria['name'] = "LIKE {$this->data['Company']['name']}%";	
			$this->set('afilter','true');								  
		}
			
		$fields = array(
			"Company.id",
			"Company.name",
			"Company.logo",
			"Company.info",
		);	

		list($order,$limit,$page) = $this->Pagination->init($criteria); // Added
		$data = $this->Company->findAll($criteria, $fields, 'Company.id DESC', $limit, $page,0); // Extra parameters added		
		//var_dump($data);
		$this->set('filter',(array_diff($criteria,$defCriteria)));
		
		$this->set('data',$data);
				
		if($this->RequestHandler->isAjax())
		{
			$this->set('xhttp',true);
		}
		//print_r($criteria);
	}
	
	function employer()
	{
		$defCriteria = aa(
		"Company.user_id",$this->othAuth->user('id')
		);

		$criteria = aa(
		"Company.user_id",$this->othAuth->user('id')
		);

		if(isset($this->params['url']['data']['Company']['name'])  AND !empty($this->params['url']['data']['Company']['name']))
		{
			$criteria['Company.name'] = "LIKE ".$this->params['url']['data']['Company']['name']."%";
		}

		if(isset($this->params['form']['data']['Company']['name'])  AND !empty($this->params['form']['data']['Company']['name']))
		{
			$criteria['name'] = "LIKE {$this->data['Company']['name']}%";
			$this->set('afilter','true');
		}
			
		$fields = array(
		"Company.id",
		"Company.name",
		"Company.logo",
		"Company.info",
		"Company.status",
		);

		list($order,$limit,$page) = $this->Pagination->init($criteria); // Added
		$data = $this->Company->findAll($criteria, $fields, 'Company.id DESC', $limit, $page,0); // Extra parameters added
		
		$this->set('filter',(array_diff($criteria,$defCriteria)));

		$this->set('data',$data);

		if($this->RequestHandler->isAjax())
		{
			$this->set('xhttp',true);
		}
		
	}
	
	
	function view($id)
	{
		$criteria = aa(
		"Company.id",$id,
		"Company.status",'1');
			
		$data = $this->Company->find($criteria,null,null,null,null,0);

		if(!is_array($data))
		{
			$this->flash('Nie znaleziono wybranej firmy!','/companies/index');
			exit();
		}
		$this->set('data', $data);
	}
	
	function view_emp($id)
	{
		$criteria = aa(
		"Company.id",$id,
		"Company.user_id",$this->othAuth->user('id'));
			
		$data = $this->Company->find($criteria,null,null,null,null,0);

		if(!is_array($data))
		{
			$this->flash('Nie znaleziono wybranej oferty!','/companies/employer');
			exit();
		}
		$this->set('data', $data);
	}


	function add()
	{
		$user_id = $this->othAuth->user('id');
		$success=true;

		if(!empty($this->data))
		{
			$this->data['Company']['user_id'] = $user_id;

			if($this->data['Company']['career_www']=="http://")
			{
				$this->data['Company']['career_www']=null;
			}

			if($this->data['Company']['www']=="http://")
			{
				$this->data['Company']['www']=null;
			}

			if($this->data['Company']['is_logo']==1)
			{
				$success = false;

				//var_dump($this->data['Company']['logo']);
				$results = $this->_checkUploadedFile($this->data['Company']['logo'],'image/gif',124*190);

				// valid upload
				if($results == 0)
				{
					// valid resize
					if($this->_resizeImg($this->data['Company']['logo']))
					{
						$success=true;
					}
					else //invalid resize
					{
						$results = 12;
					}
				}
			}
			else // w/o logo
			{
				$this->data['Company']['logo'] = null;
			}

			if($success && $this->Company->save($this->data))
			{
				$this->flash('Dane zostały zapisane.','/companies/view_emp/'.$this->Company->getID());
				exit();	
			}
			else
			{
				$this->set('errorsFound',true);
			}

			if(!$success)
			{
				$this->Company->validates($this->data);
				$this->Company->validationErrors['logo']=$this->_prepareErrMsg($results);
			}

		}
	}


	function edit($id=null)
	{
		if($id==null)
		{
			$this->redirect('/companies/add');
			exit();
		}

		$success=true;

		$this->Company->id = $id;

		$user_id = $this->othAuth->user('id');

		$company_user_id = $this->Company->read('user_id');
		$company_name = $this->Company->read('name');
		
		$logo = $this->Company->read('logo');
		
		if($logo['Company']['logo']!= null)
		{
			$this->set('logo',true);
			unset($logo);
		}
		
		

		$company_user_id = $company_user_id['Company']['user_id'];
		$company_name = $company_name['Company']['name'];

		//check permissions
		if($company_user_id != $user_id)
		{
			$this->redirect('/companies/add');
			exit();
		}

		//set view variables
		$this->set('company_name',$company_name);
		$this->set('company_id',$id);

		//if submitted ------------------------------------
		if(!empty($this->data))
		{
			$this->data['Company']['id']=$id;
			$this->data['Company']['user_id']=$user_id;


			//new logo
			if($this->data['Company']['is_logo']==2)
			{
				$success = false;

				$results = $this->_checkUploadedFile($this->data['Company']['logo'],'image/gif',124*190);

				// valid upload
				if($results == 0)
				{
					// valid resize
					if($this->_resizeImg($this->data['Company']['logo']))
					{
						$success=true;
					}
					else //invalid resize
					{
						$results = 12;
					}
				}
			}

			// del logo
			if($this->data['Company']['is_logo']==1)
			{
				$this->data['Company']['logo']=null;
			}

			if($success && $this->Company->save($this->data))
			{
				$this->flash('Dane zostały poprawnie zapisane.','/companies/view_emp/'.$this->Company->getID());
				exit();	
			}else
			{
				$this->set('errorsFound',true);
			}

			if(!$success) //logo - errors
			{
				$this->Company->validates($this->data);
				$this->Company->validationErrors['logo']=$this->_prepareErrMsg($results);
			}


		}
		else //-----------------------------------------
		{
			// set current data
			$this->data=$this->Company->read();						
		}
	}

	function delete($id)
	{
		$this->autoRender=false;
		$criteria ='Company.user_id='.$this->othAuth->user('id').' AND Company.id='.$id;

		if($this->Company->findCount($criteria)==1)
		{
			$this->Company->del($id);

			if(!$this->RequestHandler->isAjax())
			{
				$this->redirect('/company/employer');
			}
				
			$this->employer();
			$this->render('employer');
		}
		else
		{
			if(!$this->RequestHandler->isAjax())
			{
				$this->flash('Naruszenie zasad bezpieczeństwa !','/');
				exit();
			}
		}
	}

	function uhide($id,$view = null)
	{
		$this->autoRender=false;
		$criteria ="Company.user_id=".$this->othAuth->user('id')." AND Company.id=".$id;

		if($this->Company->findCount($criteria)==1)
		{
			$this->Company->id=$id;
			$current = $this->Company->read('status');
				
			if($current['Company']['status']==0)
			{
				$this->Company->saveField('status',1);
			}

			if($current['Company']['status']==1)
			{
				$this->Company->saveField('status',0);
			}
				
			if(!$this->RequestHandler->isAjax())
			{
				if($view==null)
				{
					$this->redirect('/companies/employer');
				}else
				{
					$this->redirect('/companies/view_emp/'.$id);
				}
			}
				
				
			$this->employer();
			$this->render('employer');			
		}
		else
		{
			if(!$this->RequestHandler->isAjax())
			{
				$this->flash('Naruszenie zasad bezpieczeństwa !','/');
				exit();
			}
		}
	}



	function getLogo($id)
	{
		$this->Company->id = $id;
		header("Content-type: image/gif");
		$company = $this->Company->read('logo');
		echo $company['Company']['logo'];
	}


	function getCompaniesNames()
	{
		return $this->Company->findAll(null,array('id','name'),'id',5);
	}


	function getLast()
	{
		return $this->Company->findAll('Company.status=1',array('Company.id','Company.name'),'Company.id DESC',5,null,0);
	}
	
	function getCount()
	{
		return $this->Company->findCount('Company.status=1 AND Company.user_id='.$this->othAuth->user('id'));
	}
	
	function getCountAll()
	{
		return $this->Company->findCount('Company.user_id='.$this->othAuth->user('id'));
	}

	// LOGO helps functions

	function _checkUploadedFile($file_array, $type, $size)
	{
		if(!is_array($file_array))
		{
			return 13;
		}
		if($file_array['error']!=0)
		{
			return $file_array['error'];
		}

		if($file_array['type']!=$type)
		{
			return 10;
		}

		if($file_array['size']> $size)
		{
			return 11;
		}

		return 0;
	}

	function _resizeImg(& $file_array)
	{
		$md = '/tmp/'.md5_file($file_array['tmp_name']);
		if($this->Image->imageResize($file_array['tmp_name'],$md,120,100))
		{
			$handle = fopen($md, "rb");
			$contents = fread($handle, filesize($md));
			fclose($handle);
			unlink($md);
			$file_array = $contents;
			return true;
		}
		else
		{
			$file_array = null;
			return false;
		}
	}

	function _prepareErrMsg($no)
	{
		switch ($no)
		{
			case 1:
				$msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
				break;
			case 2:
				$msg = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
				break;
			case 3:
				$msg = 'The uploaded file was only partially uploaded.';
				break;
			case 4:
				$msg = 'Podany plik nie istnieje lub nie wybrano pliku.';
				break;
			case 6:
				$msg = 'Missing a temporary folder.';
				break;
			case 7:
				$msg = 'Failed to write file to disk.';
				break;
			case 10:
				$msg = 'Zly typ - wymagany jest plik typu gif.';
				break;
			case 11:
				$msg = 'Za duzy rozmiar pliku - wymagany max to 190 kb.';
				break;
			case 12:
				$msg = 'Problem z zmiana rozmiaru loga';
				break;
			case 13:
				$msg = 'Nie wybrano pliku';
				break;

			default:
				$msg = null;
		}
		return $msg;
	}


}
?>
